package com.ybdz.scanner.base;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;

import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.ybdz.scanner.activity.LoginActivity;
import com.ybdz.scanner.receiver.ScannerInterface;
import com.ybdz.scanner.utils.ActivityCollector;
import com.ybdz.scanner.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @ClassName: BaseActivity
 * @author: zhao
 * @Description:    BaseActivity
 * @date 2017/12/11 11:00
 */
public class BaseActivity extends AppCompatActivity {


    private static ScannerInterface mScanner;
    private static IntentFilter mIntentFilter;
    private static final String RES_ACTION = "android.intent.action.SCANRESULT";
    private QMUITipDialog mShowDialog;
    private final int TIME_MAX_WAIT = 3;
    private int count;
    private Handler mHandler;
    private final int TIMER_WHAT = 100;

    private List<Activity> activityList = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mShowDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("加载中")
                .create();

        initData();

        ActivityCollector.addActivity(this);
        Log.i("Activity:",String.valueOf(this));

    }

    //当网络出现异常或者服务器出现异常时，3秒倒计时隐藏加载进度条；
    private void initData() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                {
                    switch (msg.what) {
                        case TIMER_WHAT:
                            if (count <= 0) {
                                if (mShowDialog.isShowing()){
                                    mShowDialog.dismiss();
                                }

                            } else {
                                count--;
                            }
                            break;
                    }

                }
            }
        };
    }

    protected ScannerInterface initScanner(BroadcastReceiver receiver){
        if (mScanner == null){
            mScanner = new ScannerInterface(this);
        }
        mScanner.resultScan();
        mScanner.open();                        //扫描引擎上电，该接口请勿频繁调用，频繁关闭串口会导致程序卡死
        mScanner.setOutputMode(1);              //扫描结果输出模式，此处为广播输出模式
        mScanner.unlockScanKey();               //释放设备的扫描按键，释放后iScan无法控制扫描按键，用户可自定义扫描按键
        mScanner.enablePlayBeep(true);          //是否允许蜂鸣反馈
        mScanner.enableFailurePlayBeep(false);   //扫描失败蜂鸣反馈
        mScanner.enablePlayVibrate(false);       //震动开启与关闭
        mScanner.timeOutSet(2);           //设置扫描延时2秒
        mScanner.lightSet(false);         //开启/关闭左上角扫描指示灯
        mScanner.SetErrorBroadCast(true);//扫描错误广播
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(RES_ACTION);
        this.getApplicationContext().registerReceiver(receiver, mIntentFilter);
        return mScanner;
    }

    protected void finishScanner(BroadcastReceiver receiver){
        mScanner.scan_stop();
        mScanner.continceScan(false);
//        this.getApplicationContext().unregisterReceiver(receiver);
//        mScanner.close();
    }

    /**
     * 请求成功的Dialog;
     */
    protected void showLoading(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (!activity.isFinishing()){
                mShowDialog.show();
            }
        }

        startCount();
    }

    public void startCount() {
        count = TIME_MAX_WAIT;
        final Timer timer = new Timer();
        TimerTask timeTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(TIMER_WHAT);
                if (count <= 0) {
                    if (mShowDialog.isShowing()){
                        mShowDialog.dismiss();
                    }
                    timer.cancel();
                }
            }
        };
        timer.schedule(timeTask, 1000, 1000);
    }


    protected void hideLoading() {
        if (mShowDialog.isShowing()){
            mShowDialog.dismiss();
        }
    }

    protected void showLoadinging() {
        final QMUITipDialog showDialog;
        showDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("加载中")
                .create();
        showDialog.show();
    }

    /**
     * 请求失败的Dialog;
     */
    protected void onFail(Activity activity){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (activity.isFinishing() || activity.isDestroyed()){
                return;
            }else {
                final QMUITipDialog failDialog;
                failDialog = new QMUITipDialog.Builder(this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord("请求失败")
                        .create();
                failDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        failDialog.dismiss();
                    }
                },1500 );
            }
        }
    }

    protected void onFail(Activity activity,String hint){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (activity.isDestroyed() || activity.isFinishing()){
                return;
            }else {
                final QMUITipDialog failDialog;
                failDialog = new QMUITipDialog.Builder(this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord(hint)
                        .create();
                failDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        failDialog.dismiss();
                    }
                },1500 );
            }
        }

    }

    /**
     * 请求失败的Dialog;
     */
    protected void noLogin(){
        final QMUITipDialog failDialog;
        failDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                .setTipWord("你未登录，请登录账号")
                .create();
        failDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                failDialog.dismiss();
            }
        },1500 );
    }

    /**
     * 请求超时的Dialog;
     */
    protected void onFailTimeOut(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (activity.isDestroyed() || activity.isFinishing()){
                return;
            }else {
                final QMUITipDialog failDialog;
                failDialog = new QMUITipDialog.Builder(this)//创建tipdialog实例为其设置显示样式
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)//设置有加载框模式的dialog
                        .setTipWord("网络异常，请稍后重试！")
                        .create();
                failDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        failDialog.dismiss();
                    }
                },1500 );

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}